<template>
  <div class="data-watcher">
    <div class="title">
      <span>数据监听器</span>
      <SvgIcon iconName="icon-plus" @click="addWatcher"></SvgIcon>
    </div>
    <div v-for="(item, index) in watchers" :key="item.id" class="watcher-item">
      <eForm labelPosition="left" :labelWidth="50">
        <eFormItem label="字段">
          <eInput v-model="item.key" />
        </eFormItem>
        <eFormItem label="选项">
          <eCheckboxGroup v-model="item.config">
            <eCheckbox label="deep"></eCheckbox>
            <eCheckbox label="immediate"></eCheckbox>
          </eCheckboxGroup>
        </eFormItem>
        <CodeEditor label="监听函数" v-model="item.watchFunc"></CodeEditor>
      </eForm>
      <div class="delete-btn" @click.stop="deleteWatcher(index)">
        <SvgIcon iconName="icon-closefill"></SvgIcon>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, watch } from 'vue'
  import { v4 as uuidv4 } from 'uuid'

  interface IProps {
    modelValue?: any[] | null
  }

  const props = defineProps<IProps>()

  const watchers = ref<any[]>([])

  const emit = defineEmits<{
    (e: 'update:modelValue', data: any[]): void
  }>()

  watch(
    () => props.modelValue,
    (newVal) => {
      if (newVal) {
        watchers.value = newVal
      }
    },
    { immediate: true }
  )

  function addWatcher() {
    watchers.value.push({
      id: uuidv4(),
      key: '',
      config: [],
      watchFunc: ''
    })
    emit('update:modelValue', watchers.value)
  }

  function deleteWatcher(index: number) {
    watchers.value.splice(index, 1)
    emit('update:modelValue', watchers.value)
  }
</script>

<style lang="less" scoped>
  .data-watcher {
    width: 100%;
    padding: 0 8px;
    .title {
      height: 24px;
      margin-bottom: 12px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      svg {
        cursor: pointer;
      }
    }
    .watcher-item {
      padding: 8px 4px;
      border: 1px dashed #e6e8eb;
      position: relative;
      &:not(:lastChild) {
        margin-bottom: 16px;
      }
      &:hover {
        border-color: #ed4014;
        background: #f0f0f0;
        .delete-btn {
          display: flex;
        }
      }
      .delete-btn {
        color: #2d8cf0;
        position: absolute;
        right: -12px;
        top: -12px;
        width: 24px;
        height: 24px;
        display: none;
        justify-content: center;
        align-items: center;
        cursor: pointer;
        display: none;
      }
    }
  }
</style>